package notpad_java;

import java.io.*;
import java.util.Scanner;

import javax.management.openmbean.OpenDataException;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.UndoManager;

public class Edit_frame extends JFrame{
  private  File file1;
  private	FileDialog openFileDialog;
  private	FileDialog saveFileDialog;
  private static final long serialVersionUID = -2904003336119858152L;
  //创建图像图标
  private ImageIcon newIcon = new ImageIcon("image/New.png");
  private ImageIcon openIcon = new ImageIcon("image/Open.png");
  private ImageIcon saveIcon = new ImageIcon("image/Save.png");
  private ImageIcon copyIcon = new ImageIcon("image/Copy.png");
  private ImageIcon cutIcon = new ImageIcon("image/Cut.png");
  private ImageIcon pasteIcon = new ImageIcon("image/Paste.png");
  //创建菜单条
  private JMenuBar jMenuBar = new JMenuBar();
  //创建菜单条中的菜单
  private JMenu jmuFile = new JMenu("文件(F)");
  private JMenu jmuEdit = new JMenu("编辑(E)");
  private JMenu jmuForm = new JMenu("格式(O)");
  private JMenu jmuView = new JMenu("查看(V)");
  private JMenu jmuHelp = new JMenu("帮助(H)");
  //创建菜单中的菜单项
  private JMenuItem jmtNew = new JMenuItem("新建(N)",newIcon);
  private JMenuItem jmtSave = new JMenuItem("保存(S)",saveIcon);
  private JMenuItem jmtOpen = new JMenuItem("打开(O)",openIcon);
  private JMenuItem jmtSaveAs = new JMenuItem("另存为(A)");
  private JMenuItem jmtUndo = new JMenuItem("撤销(Z)");
  private JMenuItem jmtCut = new JMenuItem("剪切(T)",cutIcon);
  private JMenuItem jmtCopy = new JMenuItem("复制(C)",copyIcon);
  private JMenuItem jmtPaste = new JMenuItem("粘贴(P)",pasteIcon);
  private JMenuItem jmtSeek = new JMenuItem("查找(F)");
  private JMenuItem jmtReplace= new JMenuItem("替换(R)");
  private JMenuItem jmtSelectALL= new JMenuItem("全选(A)");
  private JMenuItem jmtLineFeed = new JMenuItem("自动换行(W)");
  private JMenuItem jmtFont = new JMenuItem("字体(F)");
  private JMenuItem jmtStatusBar = new JMenuItem("状态栏(S)√");
  private JMenuItem jmtAbout = new JMenuItem("关于(A)");
  private JMenuItem jmtLock = new JMenuItem("加锁(L)");
  private JMenuItem jmtUnLock = new JMenuItem("解锁(U)");

  //创建工具栏
  private JToolBar jToolBar=new JToolBar(SwingConstants.VERTICAL);

  //创建工具栏中的按钮
  private JButton jbtNew = new JButton(newIcon);
  private JButton jbtOpen = new JButton(openIcon);
  private JButton jbtSave = new JButton(saveIcon);
  private JButton jbtCut = new JButton(cutIcon);
  private JButton jbtCopy = new JButton(copyIcon);
  private JButton jbtPaste = new JButton(pasteIcon);
  //创建文本域
  private static JTextArea jta = new JTextArea();
  //创建状态栏
  private JToolBar statusBar = new JToolBar();
  private static File file = null;
  private static boolean flag = false;  //标记文本是否存在
  //创建撤销管理器
  private UndoManager undoManger=new UndoManager();
  public Edit_frame(){
	  
    /**菜单条*/
    jMenuBar.add(jmuFile);       //添加文件菜单
    jmuFile.setMnemonic('F');    //设置文件菜单的热键为Alt+F
    jMenuBar.add(jmuEdit);       //添加编辑菜单
    jmuEdit.setMnemonic('E');    //设置编辑菜单的热键为Alt+E
    jMenuBar.add(jmuForm);       //添加格式菜单
    jmuForm.setMnemonic('O');    //设置格式菜单的热键为Alt+O
    jMenuBar.add(jmuView);       //添加查看菜单
    jmuView.setMnemonic('V');    //设置查看菜单的热键为Alt+V
    jMenuBar.add(jmuHelp);       //添加帮助菜单
    jmuHelp.setMnemonic('H');    //设置帮助菜单的热键为Alt+H
    //文件菜单
    jmuFile.add(jmtNew);         //添加“新建”,设置快捷键为Ctrl+N
    jmtNew.setMnemonic('N');
    jmtNew.setAccelerator(KeyStroke.getKeyStroke('N',Event.CTRL_MASK));
    jmuFile.add(jmtOpen);        //添加“打开”,设置快捷键为Ctrl+O
    jmtOpen.setMnemonic('O');
    jmtOpen.setAccelerator(KeyStroke.getKeyStroke('O',Event.CTRL_MASK));
    jmuFile.add(jmtSave);        //添加“保存”,设置快捷键为Ctrl+S
    jmtSave.setMnemonic('S');
    jmtSave.setAccelerator(KeyStroke.getKeyStroke('S',Event.CTRL_MASK));
    jmuFile.add(jmtSaveAs);      //添加“另存为”
    jmtSaveAs.setMnemonic('A');
    jmuFile.addSeparator();      //添加分隔条
    jmuFile.add(jmtLock);        //添加“加锁”
    jmtLock.setMnemonic('L');
    jmuFile.add(jmtUnLock);      //添加“解锁”
    jmtUnLock.setMnemonic('U');

    
    //编辑菜单
    jmuEdit.add(jmtUndo);        //添加“撤销”,设置快捷键为Ctrl+Z,激活状态为false
    jmtUndo.setMnemonic('Z');
    jmtUndo.setAccelerator(KeyStroke.getKeyStroke('Z',Event.CTRL_MASK));
    jmtUndo.setEnabled(false);
    jmuEdit.add(jmtCut);         //添加“剪切”,设置快捷键为Ctrl+X
    jmtCut.setMnemonic('X');
    jmtCut.setAccelerator(KeyStroke.getKeyStroke('X',Event.CTRL_MASK));
    jmuEdit.add(jmtCopy);        //添加“复制”,设置快捷键为Ctrl+C
    jmtCopy.setMnemonic('C');
    jmtCopy.setAccelerator(KeyStroke.getKeyStroke('C',Event.CTRL_MASK));
    jmuEdit.add(jmtPaste);       //添加“粘贴”,设置快捷键为Ctrl+V
    jmtPaste.setMnemonic('V');
    jmtPaste.setAccelerator(KeyStroke.getKeyStroke('V',Event.CTRL_MASK));
    jmuEdit.addSeparator();      //添加分隔条
    jmuEdit.add(jmtSeek);        //添加“查找”,设置快捷键为Ctrl+F
    jmtSeek.setMnemonic('F');
    jmtSeek.setAccelerator(KeyStroke.getKeyStroke('F',Event.CTRL_MASK));
    jmuEdit.add(jmtReplace);     //添加“替换”,设置快捷键为Ctrl+R
    jmtReplace.setMnemonic('R');
    jmtReplace.setAccelerator(KeyStroke.getKeyStroke('R',Event.CTRL_MASK));    
    jmuEdit.add(jmtSelectALL);   //添加“全选”,设置快捷键为Ctrl+A
    jmtSelectALL.setMnemonic('A');
    jmtSelectALL.setAccelerator(KeyStroke.getKeyStroke('A',Event.CTRL_MASK));    
    //格式菜单
    jmuForm.add(jmtLineFeed);    //添加“自动换行”
    jmtLineFeed.setMnemonic('W');
    jmuForm.add(jmtFont);        //添加“字体”
    jmtFont.setMnemonic('F');
    //查看菜单
    jmuView.add(jmtStatusBar);   //添加“状态栏” 
    jmtStatusBar.setMnemonic('S');
    //帮助菜单
    jmuHelp.add(jmtAbout);       //添加“关于”
    jmtAbout.setMnemonic('A');
       
    /**工具栏*/
    jToolBar.add(jbtNew);             //添加“新建”
    jToolBar.add(jbtOpen);            //添加“打开”
    jToolBar.add(jbtSave);            //添加“保存”
    jToolBar.addSeparator();          //添加分割条
    jToolBar.add(jbtCut);             //添加“剪切”
    jToolBar.add(jbtCopy);            //添加“复制”
    jToolBar.add(jbtPaste);
    //添加“粘贴”
    /**状态栏*/
    statusBar.setLayout(new FlowLayout(FlowLayout.RIGHT));
    final JLabel showLnCol=new JLabel("第1行,第0列");
    statusBar.add(showLnCol);
    getJta().addCaretListener(new CaretListener() {
  		public void caretUpdate(CaretEvent e) {
  			int Ln = 0,Col = 0;
  			try
  			  {
  			   Ln=getJta().getLineOfOffset(e.getDot())+1;
  			   Col=e.getDot()-getJta().getLineStartOffset(Ln-1);
  			  }
  			catch (Exception e1)
  			  {
  				e1.printStackTrace();
  			  }
  			showLnCol.setText("第"+Ln+"行,第"+Col+"列");
  		}
  	});   
    statusBar.setVisible(true);
    /**创建打开与保存窗口 */ 
  	openFileDialog = new FileDialog(this, "打开文件对话框", FileDialog.LOAD);
  	saveFileDialog = new FileDialog(this, "保存文件对话框", FileDialog.SAVE);
	/**创建滚动窗格并将文本域添加到窗格中 */ 
    JScrollPane scrollPane = new JScrollPane(getJta());
    
    /**添加面板到框架中*/
    setJMenuBar(jMenuBar);                //添加菜单条
    add(jToolBar, BorderLayout.WEST);     //添加工具栏
    add(scrollPane,BorderLayout.CENTER);  //添加滚动窗格
    add(statusBar,BorderLayout.SOUTH);

    /**注册监听器*/
    //新建按钮注册
    jbtNew.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	try{
          newbuilt();
    	}catch(Exception e1){}
      }	
    });
    //新建菜单项注册
    jmtNew.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	try{
          newbuilt();
        }catch(Exception e1){}         
      }	
    });
    //打开按钮注册
    jbtOpen.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        try{
    	  open();
        }catch(Exception e1){}
      }	
    });
    //打开菜单项注册
    jmtOpen.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	try{
          open();
        }catch(Exception e1){}
      }	
    });
    //保存按钮注册
    jbtSave.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        try{
          save();	
        }catch(Exception e1){}
      }	
    });
    //保存菜单项注册
    jmtSave.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	try{
          save();	
        }catch(Exception e1){}
      }	
    });
    //另存为菜单项注册
    jmtSaveAs.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	try{
          saveAs();
    	}catch(Exception e1){}    	
      }	
    });
    //加锁菜单项注册
    jmtLock.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
      	Edit_frame_encryptDialog encryptDialog=new Edit_frame_encryptDialog(Edit_frame.this);
      }	
    });
    //解锁菜单项注册
    jmtUnLock.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	Edit_frame_decryptDialog encryptDialog=new Edit_frame_decryptDialog(Edit_frame.this);
      }	
    });
    //撤销菜单项注册
    jta.getDocument().addUndoableEditListener(new UndoableEditListener() {
		public void undoableEditHappened(UndoableEditEvent e) {
			undoManger.addEdit(e.getEdit());
			jmtUndo.setEnabled(undoManger.canUndo());			
		}
	});
    jmtUndo.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			undoManger.undo();
			jmtUndo.setEnabled(undoManger.canUndo());
		}
	});	
    //剪切按钮注册
    jbtCut.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        cut();
      }	
    });
    //剪切菜单项注册
    jmtCut.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        cut();
      }	
    });
    //复制按钮注册
    jbtCopy.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        copy();
      }	
    });
    //复制菜单项注册
    jmtCopy.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        copy();
      }	
    });
    //粘贴按钮注册
    jbtPaste.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        paste();
      }	
    });
    //粘贴菜单项注册
    jmtPaste.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
        paste();
      }	
    });
  //查找菜单项注册
    jmtSeek.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){   
      	  //Edit_frame.this.setFocusable(false);
      	  Edit_frame_findDialog Seekdialog = new Edit_frame_findDialog(Edit_frame.this);
        }	
      });
  //替换菜单项注册
    jmtReplace.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){   
          Edit_frame_replace replaceDialog=new Edit_frame_replace(Edit_frame.this);
        }	
      });
  //粘贴菜单项注册
    jmtSelectALL.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){   
        	jta.setSelectionStart(0);
        	jta.setSelectionEnd(jta.getText().length());
        }	
      });
    //自动换行菜单项注册
    jmtLineFeed.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	if(getJta().getLineWrap()==false)
    		jmtLineFeed.setLabel("自动换行√");
    	else 
    		jmtLineFeed.setLabel("自动换行");
    	getJta().setLineWrap(!getJta().getLineWrap());
    	
      }	
    });
    //字体菜单项注册
    jmtFont.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
    	  Edit_frame.this.setFocusable(false);
    	  Edit_frame_FontSet fontdialog = new Edit_frame_FontSet(Edit_frame.this);
      }	
    });
    //状态栏菜单项注册
    jmtStatusBar.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	if (statusBar.isVisible())
    		jmtStatusBar.setText("状态栏 ");
    	else
    		jmtStatusBar.setText("状态栏√");
    	statusBar.setVisible(!(statusBar.isVisible()));
      }	
    });
    //关于菜单项注册
    jmtAbout.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){   
    	JOptionPane.showMessageDialog(null,"13级信息管理与信息系统4班\n by 赵荐轩 陈家辉 陈伟林 胡心怡","关于",JOptionPane.INFORMATION_MESSAGE);
      }	
    });
  }
  
  /**新建、打开、保存、另存为、剪切、复制、粘贴功能实现*/
  //新建
  private void newbuilt() throws IOException{
		int option;
		if(!((jta.getText()).equals(""))){
			option=JOptionPane.showConfirmDialog(null,"是否保存当前文件",
		    	     "打开",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
	      if(option == JOptionPane.YES_OPTION){
	    	save();
	        jta.setText("");
	        this.setTitle("无标题 - 简易文本编辑器");
	        flag = false;
	      }
	      else if(option == JOptionPane.NO_OPTION){
	    	jta.setText("");
	        this.setTitle("无标题 - 简易文本编辑器");
	        flag = false;
	      }
	      else{
	      }
	    }	
		
	}
  //打开
  private void open() throws IOException{
		int option;
		openFileDialog = new FileDialog(this, "打开文件对话框", FileDialog.LOAD);
		String path=null;
	    //如果文本为空，直接打开
		if(file1==null){
	      openFileDialog.setVisible(true);
		   if (openFileDialog.getDirectory() != null && openFileDialog.getFile() != null) 
		   {
				path = openFileDialog.getDirectory()+ openFileDialog.getFile();	    
		   }
		}
		//如果文本不为空，先询问是否保存再打开
		else {
			option=JOptionPane.showConfirmDialog(null,"是否保存当前文件",
		    	     "打开",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
		      if(option == JOptionPane.YES_OPTION){
		        save();
		        openFileDialog.setVisible(true);
				if (openFileDialog.getDirectory() != null && openFileDialog.getFile() != null) 
				{
				   path = openFileDialog.getDirectory()+ openFileDialog.getFile();	    
				 }
		      }
		      else if(option == JOptionPane.NO_OPTION){
			     openFileDialog.setVisible(true);
				 if (openFileDialog.getDirectory() != null && openFileDialog.getFile() != null) 
				 {
					path = openFileDialog.getDirectory()+ openFileDialog.getFile();	    
				 }
		      }
		}	
		//读取打开文本里的内容（打开的主要操作）
	    if(path != null){
	      jta.setText("");
		  this.setTitle(path);
		  file1=new File(openFileDialog.getDirectory(),openFileDialog.getFile());
		  FileReader fr = new FileReader(file1);
		  BufferedReader br=new BufferedReader(fr);
		  String aline;
		  while ((aline=br.readLine())!=null)//按行读取文本     
		  jta.append(aline+"\r\n");
		  fr.close();
		  br.close();
		  }
		  flag = true;
		}
		  

  //保存
  private void save() throws IOException{
		//新建内容直另存为
		if(file1==null){
		  saveAs();
		}
		//打开文本直接保存
		else{
		    PrintStream output = new PrintStream(new FileOutputStream(file1));
		    output.print(jta.getText());
		    output.close();
		  }
		flag = true;
	  }
  //另存为
  private void saveAs() throws IOException{	
    int result = 0 ;	
	saveFileDialog=new FileDialog(this, "保存文件对话框", FileDialog.SAVE);
	if (file1==null) saveFileDialog.setName("未命名");
	else             saveFileDialog.setName(file1.getName());
	saveFileDialog.setVisible(true);
	if ((saveFileDialog.getDirectory()!=null) && (saveFileDialog.getFile()!=null)){ 
	   file1 = new File(saveFileDialog.getDirectory(),saveFileDialog.getFile()); 
} 
	if(file1 != null){
	  PrintStream output = new PrintStream(new FileOutputStream(file1));
	  output.print(getJta().getText());
	  output.close();
	}
	flag = true;
  }
  //剪切
  private void cut(){
	getJta().cut();
  }
  //复制
  private void copy(){
	getJta().copy();	  
  }
  //粘贴
  private void paste(){
	getJta().paste();  
  }

  public static JTextArea getJta() {
	return jta;
  }

public void setJta(JTextArea jta) {
	this.jta = jta;
}
class Edit_frame_FontSet extends JDialog implements ActionListener,ItemListener,WindowListener
{
  /**
	 * 
	 */
	private static final long serialVersionUID = -283424513814862982L;
  private JButton okButton=new JButton("确定");
  private JButton cancelButton=new JButton("取消"); 
  private String  fontName;
  private int     fontSize;
  private JComboBox fontName_combox;
  private JComboBox fontSize_combox;
  private Font font;
  private JLabel fontDisplay;
  private Edit_frame_FontSet(Edit_frame windown)
  {
	  //窗口基本属性设置
	  
	  GridLayout grid=new GridLayout(4,2);
	  setLayout(grid);
	  setModal(true);
	  setTitle("字体");
	  setSize(330,210);
	  setLocationRelativeTo(windown);
	  this.addWindowListener((WindowListener) this); 
	  this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
	  okButton.addActionListener(this);;
	  cancelButton.addActionListener(this);
	  //当前文本域属性
	  font = Edit_frame.getJta().getFont();
	  fontSize = font.getSize();
	  fontName = font.getName();
	  //获取系统所有字体
	  GraphicsEnvironment ge =GraphicsEnvironment.getLocalGraphicsEnvironment();
	  String[] fontNames=ge.getAvailableFontFamilyNames();
	  
	  //字体与字体大小的下拉菜单
	  JLabel nameLable=new JLabel("字体");
	  JLabel sizeLable=new JLabel("大小");
	  fontName_combox=new JComboBox(fontNames);
	  fontName_combox.addItemListener(this);
	  String[] size = {"8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "32", "34", "42", "52", "62", "72"};
	  fontSize_combox=new JComboBox(size);
	  fontSize_combox.addItemListener(this);
	  
	  //预览窗口
	  JLabel previewlable=new JLabel("字体预览");
	  fontDisplay = new JLabel("Java 字体预览");
	  fontDisplay.setFont(font);
	  JPanel displayPanel = new JPanel(true);
	  displayPanel.setBackground(Color.WHITE);
	  displayPanel.add(fontDisplay);
	  
	  //组合面板
	  add(nameLable);
	  add(fontName_combox);
	  add(sizeLable);
	  add(fontSize_combox);
	  add(previewlable);
	  add(displayPanel);
	  add(okButton);
	  add(cancelButton);
	  setVisible(true);
	  
	  		 
  }
@Override
public void itemStateChanged(ItemEvent e) {
	if (e.getSource()==fontName_combox)
	 fontName=(String)fontName_combox.getSelectedItem();
	if (e.getSource()==fontSize_combox)
	 fontSize=Integer.parseInt((String)fontSize_combox.getSelectedItem());
	font = new Font(fontName, font.PLAIN, fontSize);
	fontDisplay.setFont(font);
	fontDisplay.repaint();	
}
@Override
public void actionPerformed(ActionEvent e) {
	if (e.getSource()==okButton)
	{
		Edit_frame.getJta().setFont(font);
		setVisible(false);
		
	}
	if (e.getSource()==cancelButton)
	{
		setVisible(false);
	}
	Edit_frame_FontSet.this.setFocusable(true);
}
@Override
public void windowActivated(WindowEvent e) {
	// TODO 自动生成的方法存根
	
}
@Override
public void windowClosed(WindowEvent e) {
	// TODO 自动生成的方法存根
	
}
@Override
public void windowClosing(WindowEvent e) {
	Edit_frame.this.setEnabled(true);
	dispose();
}
@Override
public void windowDeactivated(WindowEvent e) {
	// TODO 自动生成的方法存根
	
}
@Override
public void windowDeiconified(WindowEvent e) {
	// TODO 自动生成的方法存根
	
}
@Override
public void windowIconified(WindowEvent e) {
	// TODO 自动生成的方法存根
	
}
@Override
public void windowOpened(WindowEvent e) {
	// TODO 自动生成的方法存根
	
}

}

}